package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.domain.SubCategory;
import cc.eddic.practice.spring.dto.CategoryAddRequest;
import cc.eddic.practice.spring.dto.CategoryResponse;
import cc.eddic.practice.spring.dto.SubCategoryAddRequest;
import cc.eddic.practice.spring.dto.SubCategoryResponse;
import cc.eddic.practice.spring.repository.CategoryRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.transaction.Transactional;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/categories")
public class CategoryRestController {
    public CategoryRestController(CategoryRepository repository){this.repository=repository;}
    private final CategoryRepository repository;
    @PostMapping
    public HttpEntity<?> add(@RequestBody final CategoryAddRequest model){
        val category=repository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(category.getId()).toUri()).build();
    }
    @Transactional
    @PostMapping("/{categoryId}/subCategories")
    public HttpEntity<?> add(@PathVariable("categoryId") Long categoryId, @RequestBody final SubCategoryAddRequest model){
        val category=repository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subCategory=model.as();
        category.add(subCategory);
        repository.save(category);
        if (log.isDebugEnabled())log.debug(" sub category id {}",subCategory.getId());
        val id=category.getSubCategories().stream().filter(x->x.getName().equals(model.getName()))
                .sorted(Comparator.comparing(SubCategory::getCreatedOn).reversed())
                .map(SubCategory::getId)
                .findFirst()
                .orElse(-1L);
        if (log.isDebugEnabled()){
            log.debug("sub category id {}",subCategory.getId());
            log.debug("(filter) sub category id {}",id);
        }
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{categoryId}/subCategories/{subCategoryId}")
                .buildAndExpand(category.getId(),id).toUri()).build();
    }
//获取类中所有子类信息
    @GetMapping("/{categoryId}/subCategories")
    public HttpEntity<?> get(@PathVariable("categoryId") Long categoryId){
        if (log.isDebugEnabled()) log.debug("categoryId={}",categoryId);
        val category=repository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(category.getSubCategories().stream().map(SubCategoryResponse::from).collect(Collectors.toList()));
    }
//根据子类ID获取信息
    @GetMapping("/{categoryId}/subCategories/{subCategoryId}")
    public HttpEntity<?> get(@PathVariable("categoryId") Long categoryId,@PathVariable("subCategoryId") Long subCategoryId){
        val category=repository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subcategory=category.getSubCategories().stream().filter(subCategory->subCategory.getId().equals(subCategoryId)).findFirst()
                .orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(SubCategoryResponse.from(subcategory));
    }
    @GetMapping("/{id}")
    public HttpEntity<CategoryResponse> get(@PathVariable("id") final long id){
        if(log.isDebugEnabled()) log.debug("id={}",id);
        val category=repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(CategoryResponse.from(category));
    }
    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id){
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping
    public HttpEntity<List<CategoryResponse>> getAll(){
        val category=repository.findAll().stream().map(CategoryResponse::from).collect(Collectors.toList());
        return ResponseEntity.ok(category);
    }
}
